package com.ziytek.web.citizen.service.impl;

import com.ziytek.web.citizen.config.caffeine.CaffeineUtil;
import com.ziytek.web.citizen.constant.ServerConstant;
import com.ziytek.web.citizen.mapper.BasicCabinetIpMapper;
import com.ziytek.web.citizen.model.bean.OfflineInfo;
import com.ziytek.web.citizen.model.vo.StatusVo;
import com.ziytek.web.citizen.service.itf.OfflineService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author fenghx
 * @version 1.0
 * @className OfflineServiceImpl
 * Description: 设备离线
 * @date 2024/6/3 16:28
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class OfflineServiceImpl implements OfflineService {
    private final BasicCabinetIpMapper cabinetIpMapper;


    @Override
    public List<OfflineInfo> offline(String token) {
        //Map<String, OfflineInfo> offlineMap = IpCacheManager.getAllOffline();
        var offlineCacheMap = CaffeineUtil.getAllStartWith(CaffeineUtil.CACHE_KEY_OFFLINE);
        Map<String, OfflineInfo> offlineMap = new HashMap<>();
        offlineCacheMap.forEach((k, v) -> {
            log.info("offlineCacheMap key:{}, value:{}", k, v);
            offlineMap.put(k.replace(CaffeineUtil.CACHE_KEY_OFFLINE, ""), (OfflineInfo) v.data);
        });
        if (CollectionUtils.isEmpty(offlineMap)) {
            return Collections.emptyList();
        }

        List<OfflineInfo> offlineInfos = new ArrayList<>();
        for (var ip : offlineMap.keySet()) {
            var ipTbl = cabinetIpMapper.queryCabinetIpInfoByIp(ip);
            var offlineInfo = offlineMap.getOrDefault(ip, null);
            if (ipTbl != null && offlineInfo != null) {
                OfflineInfo off = new OfflineInfo();
                off.setCabinetNo(ipTbl.getCabinetNo());
                off.setOfflineReason(offlineInfo.getOfflineReason());
                off.setOfflineTime(offlineInfo.getOfflineTime());
                offlineInfos.add(off);
            }
        }

        return offlineInfos.isEmpty() ? Collections.emptyList() : offlineInfos;
    }

    @Override
    public boolean online(Integer cabinetNo) {
        var key = "statusVo_key_" + cabinetNo;
        StatusVo statusVo = CaffeineUtil.get(key);
        return statusVo != null && ServerConstant.STATUS_ONLINE.equals(statusVo.getStatus());
    }
}
